/**
 * Project Name:cnsy-url-short-service
 * File Name:TreeMenuUtil.java
 * Package Name:cn.cnsy123.shorturls.business.util 
 * Date: 2020年4月17日-上午9:27:49
 * Copyright (c) 2020, yangpengfei@360@126.com All Rights Reserved. 
 *
 */

package cn.cnsy123.shorturls.business.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.util.CollectionUtils;

import cn.cnsy123.shorturls.api.controller.result.SysMenuResult;
import cn.cnsy123.shorturls.api.controller.vo.TreeMenuVo;

/**
 * ClassName: TreeMenuUtil
 * 
 * @author yangpengfei
 * @date 2020年4月17日-上午9:27:49
 * @version 1.0
 * @since JDK 1.7
 */
public class TreeMenuUtil {
    
    public static SysMenuResult getFirstPageNode(List<TreeMenuVo> treeMenus) {
        Integer isPage = treeMenus.get(0).getSysMenu().getIsPage();
        if(isPage != null && isPage.intValue() == 0) {
            if(!CollectionUtils.isEmpty(treeMenus.get(0).getChildren())) {
                return getFirstPageNode(treeMenus.get(0).getChildren());
            }
        }
        return treeMenus.get(0).getSysMenu();
    }

    public static List<Long> getParentId(final Map<String, SysMenuResult> indexData,final Long id) {
        List<Long> list = new ArrayList<Long>();
        SysMenuResult sysMenuResult = indexData.get(id.toString());
        if(sysMenuResult != null && sysMenuResult.getPid() != null) {
            list.add(sysMenuResult.getPid());
            list.addAll(getParentId(indexData,sysMenuResult.getPid()));
        }
        return list;
    }

    public static Map<String, SysMenuResult> convertDataById(final List<TreeMenuVo> treeMenus) {
        Map<String, SysMenuResult> map = new HashMap<String, SysMenuResult>();
        for(TreeMenuVo treeMenuVo:treeMenus) {
            SysMenuResult sysMenu = treeMenuVo.getSysMenu();
            map.put(sysMenu.getId().toString(), sysMenu);
            List<TreeMenuVo> children = treeMenuVo.getChildren();
            if(!CollectionUtils.isEmpty(children)) {
                map.putAll(convertDataById(children));
            }
        }
        return map;
    }
    
    public static Map<String, SysMenuResult> convertDataByMenuUrl(final List<TreeMenuVo> treeMenus) {
        Map<String, SysMenuResult> map = new HashMap<String, SysMenuResult>();
        for(TreeMenuVo treeMenuVo:treeMenus) {
            SysMenuResult sysMenu = treeMenuVo.getSysMenu();
            map.put(sysMenu.getMenuUrl(), sysMenu);
            List<TreeMenuVo> children = treeMenuVo.getChildren();
            if(!CollectionUtils.isEmpty(children)) {
                map.putAll(convertDataByMenuUrl(children));
            }
        }
        return map;
    }

}
